package v1

import (
	"encoding/json"
	"errors"
	"net/http"
)

type Context struct {
	Req  *http.Request
	Resp http.ResponseWriter

	RespStatusCode int
	RespData       []byte
}

func (c *Context) BindJSON(val any) error {
	if c.Req.Body == nil {
		return errors.New("body is nil")
	}

	decoder := json.NewDecoder(c.Req.Body)
	decoder.DisallowUnknownFields()
	return decoder.Decode(val)

}

func (c *Context) RespJSONOK(val any) error {
	return c.RespJSON(http.StatusOK, val)
}

func (c *Context) RespJSON(code int, val any) error {
	bs, err := json.Marshal(val)
	if err != nil {
		return err
	}
	c.RespStatusCode = code
	c.RespData = bs

	//json.Marshal(c)
	//c.Resp.Write([]byte(c))
	c.Resp.WriteHeader(code)
	c.Resp.Write(c.RespData)
	return nil
}
